package com.repair.util;

import com.repair.config.BaiduMapConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Component
public class BaiduMapUtil {

    @Autowired
    private BaiduMapConfig baiduMapConfig;

    @Autowired
    private RestTemplate restTemplate;

    private static final String GEOCODING_URL = "http://api.map.baidu.com/geocoding/v3/";
    private static final String ROUTE_PLANNING_URL = "http://api.map.baidu.com/directionlite/v1/driving";

    public Map<String, Double> geocoding(String address) {
        Map<String, String> params = new HashMap<>();
        params.put("address", address);
        params.put("output", "json");
        params.put("ak", baiduMapConfig.getAk());

        Map<String, Object> response = restTemplate.getForObject(
                GEOCODING_URL + "?address={address}&output={output}&ak={ak}",
                Map.class,
                params
        );

        if (response != null && "0".equals(response.get("status"))) {
            Map<String, Object> location = (Map<String, Object>) response.get("result");
            Map<String, Double> result = new HashMap<>();
            result.put("lng", Double.parseDouble(location.get("location").toString().split(",")[0]));
            result.put("lat", Double.parseDouble(location.get("location").toString().split(",")[1]));
            return result;
        }
        return null;
    }

    public Map<String, Object> getRoute(String origin, String destination) {
        Map<String, String> params = new HashMap<>();
        params.put("origin", origin);
        params.put("destination", destination);
        params.put("ak", baiduMapConfig.getAk());

        return restTemplate.getForObject(
                ROUTE_PLANNING_URL + "?origin={origin}&destination={destination}&ak={ak}",
                Map.class,
                params
        );
    }

    public double calculateDistance(double lat1, double lng1, double lat2, double lng2) {
        double R = 6371.0; // 地球半径，单位km
        double dLat = Math.toRadians(lat2 - lat1);
        double dLng = Math.toRadians(lng2 - lng1);
        double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
                Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
                        Math.sin(dLng / 2) * Math.sin(dLng / 2);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        return R * c;
    }
} 